package top.qitun.tian.controller;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import top.qitun.bizz.user.request.modal.RegisterRequest;
import top.qitun.bizz.user.tuser.entity.TUserBO;
import top.qitun.common.api.response.ReturnResponse;
import top.qitun.common.utils.StringHelper;
import top.qitun.model.response.ObjectDataResponse;
import top.qitun.tian.api.UserManagementServiceAPI;
import top.qitun.tian.util.AbstractTokenUtil;
import top.qitun.tian.util.JsonWebTokenUtility;
import top.qitun.tian.util.WebUtils;
import top.qitun.tian.util.modal.AuthUser;

/**
 * The type User controller.
 *
 * @author zhangxd
 */
@Validated
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    /**
     * 用户服务
     */
//    @Autowired
//    private ITripUserService tripUserService;
    /**
     * 验证码服务
     */
//    @Autowired
//    private ICaptchaService captchaService;
	@Value("${spring.cloud.config.profile}")
	private String profile;
    /**
     * 密码加密
     */
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
	private UserManagementServiceAPI userManagementServiceAPI;
    /**
     * 文件管理
     */
//    @Autowired
//    private FileManager fileManager;

    /**
     * Registry user map.
     *
     * @param version    the version
     * @param password   the password
     * @param mobile     the mobile
     * @param captcha    the captcha
     * @param invitation the invitation
     * @return the map
     * @throws InvalidCaptchaException the invalid captcha exception
     */
    @PostMapping(value = "register", produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "注册用户")
    public ReturnResponse<TUserBO> registryUser(@RequestBody RegisterRequest registerRequest) throws Exception {
        //校验验证码
//        captchaService.validCaptcha(mobile, captcha);
    	// Authenticate the user
    	registerRequest.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
    	ObjectDataResponse<TUserBO> respose = userManagementServiceAPI.register(registerRequest);
    	if (respose.getCode() != 0) {
			return new ReturnResponse<>(respose.getCode(), respose.getMessage());
		} else {
			TUserBO user = respose.getData();
			user.setExpirationDate(buildExpirationDate());
			// Create auth token
			String jwt = JsonWebTokenUtility.createJsonWebToken(user);
			if (jwt != null) {
				user.setToken(jwt);
			}

			return new ReturnResponse<TUserBO>(0, "注册成功", user);
		}
    }
    
    private Date buildExpirationDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR_OF_DAY, 1);
		Date expirationDate = calendar.getTime();
		return expirationDate;
	}

    /**
     * Gets user.
     *
     * @param version the version
     * @return the user
     */
    @GetMapping(value = "/me", produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "获取用户信息")
    @ApiImplicitParams(
        {
            @ApiImplicitParam(name = "Authorization", required = true, paramType = "header",
                dataType = "string", value = "authorization header", defaultValue = "Bearer ")
        }
    )
    public ReturnResponse<TUserBO> me(ServletRequest request) {
    	HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authHeader = httpRequest.getHeader(AbstractTokenUtil.TOKEN_HEADER);

        final String authToken = StringHelper.substring(authHeader, 7);
        String username = StringHelper.isNotBlank(authToken) ? JsonWebTokenUtility.getUsernameFromToken(authToken) : null;
        TUserBO user = new TUserBO();
        user.setMobile(username);
        return new ReturnResponse<TUserBO>(0, "获取用户信息", user);
//    	if("dev".equals(profile)){
//    		TUserBO userBO= new TUserBO();
//	        userBO.setMobile("18565817096");
//	        return new ReturnResponse<TUserBO>(0, "获取用户信息", userBO);
//    	}else{
//	        AuthUser user = WebUtils.getCurrentUser();
//	        TUserBO userBO= new TUserBO();
//	        userBO.setMobile(user.getMobile());
//	        return new ReturnResponse<TUserBO>(0, "获取用户信息", userBO);
//    	}
    }

}
